package com.android.webttest.View;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.android.webttest.Adapter.SearchHistoryAdapter;

import com.android.webttest.model.tableModel.SearchHistoryRecord;
import com.android.webttest.R;
import com.android.webttest.utils.RoomDBTools;
import com.android.webttest.utils.StatusBarUtil;
import com.android.webttest.utils.Tools;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.material.textfield.TextInputEditText;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SearchGoodView extends AppCompatActivity {

    private FlexboxLayoutManager manager;
    private RecyclerView goodSearchHistory;

    private TextInputEditText searchEditText; // 搜索输入框

    private ImageButton iconSearchBack;
    private ImageButton clearHistoryButton;

    private Button good_search_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_search_good_view);


        // 使用工具类设置状态栏
        StatusBarUtil.setImmersiveStatusBarR(this);

        iconSearchBack = findViewById(R.id.icon_search_back);
        iconSearchBack.setOnClickListener(v -> {
            finish();
        });
        clearHistoryButton = findViewById(R.id.clear_history_button);
        clearHistoryButton.setOnClickListener(v -> {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.execute(() -> {
                List<SearchHistoryRecord> historyList = RoomDBTools.getAllSearchHistory();

                runOnUiThread(() -> {
                    if (historyList != null && !historyList.isEmpty()) {
                        // 有历史，显示确认对话框
                        new androidx.appcompat.app.AlertDialog.Builder(SearchGoodView.this)
                                .setTitle("清空历史记录")
                                .setMessage("确定要删除所有搜索历史吗？")
                                .setPositiveButton("确定", (dialog, which) -> {
                                    ExecutorService deleteExecutor = Executors.newSingleThreadExecutor();
                                    deleteExecutor.execute(() -> {
                                        RoomDBTools.deleteAllSearchHistory();
                                        runOnUiThread(() -> goodSearchHistory.setVisibility(View.GONE));
                                    });
                                })
                                .setNegativeButton("取消", null)
                                .show();
                    } else {
                        // 没有历史，弹出警告提示
                        new androidx.appcompat.app.AlertDialog.Builder(SearchGoodView.this)
                                .setTitle("提示")
                                .setMessage("暂无历史可删除")
                                .setPositiveButton("确定", null)
                                .show();
                    }
                });
            });
        });

//

        goodSearchHistory = findViewById(R.id.good_search_history_list);
        searchEditText = findViewById(R.id.good_search_edit_text);
        //历史记录的LayoutManager
        manager = new FlexboxLayoutManager(this);
        //设置主轴排列方式
        manager.setFlexDirection(FlexDirection.ROW);
        //设置是否换行
        manager.setFlexWrap(FlexWrap.WRAP);
        manager.setAlignItems(AlignItems.STRETCH);

//        // 加载搜索历史
        history();

        good_search_button = findViewById(R.id.good_search_button);
        good_search_button.setOnClickListener(v -> {
            String query = searchEditText.getText() == null ? null : searchEditText.getText().toString().trim();
            if (query == null || query.isEmpty()) {
                Tools.Toast(this, "请输入搜索内容");
            } else {
                // 使用线程池执行数据库操作
                ExecutorService executor = Executors.newSingleThreadExecutor();
                executor.execute(() -> {
                    // 执行数据库操作
                    RoomDBTools.updateOrInsertSearchHistory(query);

                    // 可选：更新历史记录列表（需要回到主线程）
                    runOnUiThread(() -> {
                        history(); // 刷新历史记录列表
                    });
                });
                //清空
                searchEditText.setText(null);
            }
        });
    }

    //填充历史搜索
    private void history() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            List<SearchHistoryRecord> historyRecordList = RoomDBTools.getAllSearchHistory();

            // 回到主线程更新 UI
            runOnUiThread(() -> {
                goodSearchHistory.setLayoutManager(manager);

                if (historyRecordList != null && !historyRecordList.isEmpty()) {
                    SearchHistoryAdapter adapter = new SearchHistoryAdapter(this, historyRecordList, pos -> {
                        SearchHistoryRecord record = historyRecordList.get(pos);
                        String query = record.getQuery();
                        searchEditText.setText(query); // 填充到搜索框
                    });

                    goodSearchHistory.setAdapter(adapter);
                    goodSearchHistory.setVisibility(View.VISIBLE);
                } else {
                    goodSearchHistory.setVisibility(View.GONE);
                }
            });
        });
    }
    private String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(new Date());
    }


}